package jjn.round1;

/**
 * @author Jjn
 * @since 2022/10/1 22:30
 */
public class LeetCode1694_ReformatPhoneNumber {
    public String reformatNumber(String number) {
        char[] filterData = new char[number.length()];
        int size = 0;
        for (int i = 0; i < number.length(); i++) {
            if (Character.isDigit(number.charAt(i))) {
                filterData[size++] = number.charAt(i);
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        int remain = size;
        while (remain > 0) {
            if (remain > 4) {
                int start = size - remain;
                int end = size - remain + 3;
                for (int i = start; i < end; i++) {
                    stringBuilder.append(filterData[i]);
                    remain--;
                }
                stringBuilder.append("-");
            }
            if (remain == 4) {
                int start = size - remain;
                for (int i = start; i < size; i++) {
                    if (i == start + 2) {
                        stringBuilder.append("-");
                    }
                    stringBuilder.append(filterData[i]);
                    remain--;
                }
            }
            if (remain < 4) {
                for (int i = size - remain; i < size; i++) {
                    stringBuilder.append(filterData[i]);
                    remain--;
                }
            }
        }
        return stringBuilder.toString();
    }
}
